package com.guagua.vas.homepage.database;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class DatabaseObjectIterator implements Iterator{

	private int objectType;
	private long elements[];
	private int currentIndex;
	private Object nextElement;

	public static final Iterator EMPTY_ITERATOR = new DatabaseObjectIterator(){

		public boolean hasNext() {
			return false;
		}

		public Object next() {
			throw new NoSuchElementException();
		}

		public boolean hasPrevious() {
			return false;
		}

		public Object previous() {
			throw new NoSuchElementException();
		}

	};

	public DatabaseObjectIterator() {}

	public DatabaseObjectIterator(int type, long elements[]) {
		currentIndex = -1;
		nextElement = null;
		if (!DatabaseObjectLoader.isKnownType(type)) {
			throw new IllegalArgumentException("Unknown object type: " + type);
		} else {
			objectType = type;
			this.elements = elements;
			return;
		}
	}

	public boolean hasNext() {
		if (elements == null || currentIndex + 1 >= elements.length && nextElement == null)
			return false;
		if (nextElement == null) {
			nextElement = getNextElement();
			if (nextElement == null)
				return false;
		}
		return true;
	}

	public Object next() throws NoSuchElementException {
		Object element = null;
		if (nextElement != null) {
			element = nextElement;
			nextElement = null;
		} else {
			element = getNextElement();
			if (element == null)
				throw new NoSuchElementException();
		}
		return element;
	}

	public void remove() throws UnsupportedOperationException {
		throw new UnsupportedOperationException();
	}

	public Object getNextElement() {
		if (elements == null)
			return null;
		while (currentIndex + 1 < elements.length) {
			currentIndex++;
			Object element = DatabaseObjectLoader.getBaduObject(objectType, elements[currentIndex]);
			if (element != null)
				return element;
		}
		return null;
	}
}
